/*
 * @Descripttion: 
 * @version: 
 * @Author: wutao
 * @LastEditors: wutao
 * @LastEditTime: 2025-07-19 23:40:06
 */
import axios from 'axios';
import { Toast } from 'vant'; // 如果你用 vant，换成你项目的提示组件即可

const BASE_URL = ""; // 根据你项目修改，或者.env中配置

// 创建 axios 实例
const service = axios.create({
  baseURL: BASE_URL,
  timeout: 10000, // 10秒超时
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 自动带 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    // 其他请求前处理...
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 这里按你接口规则判断
    if (res.code && res.code !== 0) {
      Toast.fail(res.message || '请求错误');
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  },
  (error) => {
    // 网络或服务器错误统一提示
    Toast.fail(error.message || '网络错误，请稍后重试');
    return Promise.reject(error);
  }
);

// get 请求
function get(url, params = {}, config = {}) {
  return service.get(url, { params, ...config });
}

// post 请求
function post(url, data = {}, config = {}) {
  return service.post(url, data, config);
}

// put 请求
function put(url, data = {}, config = {}) {
  return service.put(url, data, config);
}

// delete 请求
function del(url, params = {}, config = {}) {
  return service.delete(url, { params, ...config });
}

export default {
  get,
  post,
  put,
  delete: del,
  service, // 如果你需要直接用 axios 实例
};
